package top.wardyan.wmes.rfid.kqa.util;

import java.io.UnsupportedEncodingException;

import top.wardyan.wmes.rfid.kqa.vo.BaseConsumeException;

/**
 * @author lcf
 * @CreateTime 2022/1/25 17:41
 * @Description
 */
public class DataChangeHelper {
    //16进制转10进制
    public static int hexToInt(String str){
        int r = 0, j = 0;
        String sub = "";
        for(int i = str.length(); i >= 1; i--){
            int compare = 0;
            sub =  str.substring(i-1, i);
            if (sub.toUpperCase().equals("A")) {
                compare = 10;
            } else if(sub.toUpperCase().equals("B")) {
                compare = 11;
            } else if(sub.toUpperCase().equals("C")) {
                compare = 12;
            } else if(sub.toUpperCase().equals("D")) {
                compare = 13;
            } else if(sub.toUpperCase().equals("E")) {
                compare = 14;
            } else if(sub.toUpperCase().equals("F")) {
                compare = 15;
            }else {
                compare = Integer.valueOf(sub);
            }
            r += compare * Math.pow(16, j);
            j += 1;
        }
        return r;
    }


    public static String convertHexToString(String hex){

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for( int i=0; i<hex.length()-1; i+=2 ){

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char)decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }
    public static String strToGB2312(String str) {
        try {
            byte[] bytes = str.getBytes("gb2312");// 先把字符串按gb2312转成byte数组
            StringBuilder gbStr = new StringBuilder();
            for (byte b : bytes)// 循环数组
            {
                String temp = Integer.toHexString(b);// 再用Integer中的方法，把每个byte转换成16进制输出
                temp = temp.substring(6, 8); // 截取
                gbStr.append(temp);
            }
            return gbStr.toString();
        } catch (UnsupportedEncodingException e) {
            throw new BaseConsumeException("字符串转GBK2312码异常");
        }
    }
}
